package com.lihaozhe.restclient.controller;

import com.lihaozhe.restclient.dto.ProductDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 商品模拟服务控制器
 * 用于模拟商品服务的API，便于测试RestClient调用
 * 实际项目中这个应该是一个独立的微服务
 *
 * @author 李昊哲
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/products")
public class ProductMockController {
  private static final Logger log = LoggerFactory.getLogger(ProductMockController.class);
  // 模拟商品数据
  private final List<ProductDTO> mockProducts = Arrays.asList(
      new ProductDTO(1L, "iPhone 15", 5999.00, 100),
      new ProductDTO(2L, "MacBook Pro", 12999.00, 50),
      new ProductDTO(3L, "AirPods Pro", 1899.00, 200)
  );

  /**
   * 根据ID获取商品
   * GET /api/products/{id}
   */
  @GetMapping("/{id}")
  public ProductDTO getProduct(@PathVariable("id") Long id) {
    // 模拟网络延迟
    simulateDelay();

    return mockProducts.stream()
        .filter(p -> p.getId().equals(id))
        .findFirst()
        .orElse(new ProductDTO(id, "未知商品", 0.0, 0));
  }

  /**
   * 获取所有商品
   * GET /api/products
   */
  @GetMapping
  public List<ProductDTO> getAllProducts() {
    // 模拟网络延迟
    simulateDelay();
    return mockProducts;
  }

  /**
   * 更新商品库存
   * PUT /api/products/{id}/stock
   */
  @PutMapping("/{id}/stock")
  public String updateStock(@PathVariable("id") Long id, @RequestBody Map<String, Integer> request) {
    Integer quantity = request.get("quantity");
    log.info("更新商品 {} 库存，变化数量: {}", id, quantity);
    // 模拟网络延迟
    simulateDelay();
    // 模拟库存更新逻辑
    return "success";
  }

  /**
   * 模拟网络延迟
   */
  private void simulateDelay() {
    try {
      Thread.sleep(ThreadLocalRandom.current().nextInt(200, 1000)); // 100ms延迟，模拟真实网络请求
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
}
